<template>
    <div class="add-cargo-owner-page">
        <div class="page-title">新增货主</div>

        <div class="form card">
            <div class="form-item required">
                <label class="label">货主姓名：</label>
                <input class="input" v-model.trim="form.name" placeholder="请输入货主姓名" />
            </div>

            <div class="form-item required">
                <label class="label">手机号：</label>
                <input class="input" v-model.trim="form.phone" placeholder="请输入手机号" />
            </div>

            <div class="form-item required">
                <label class="label">单位名称：</label>
                <select class="input" v-model="form.company" @change="onCompanyChange">
                    <option value="" disabled>请选择单位名称</option>
                    <option v-for="u in externalUnitOptions" :key="u.id" :value="u.unitName">{{ u.unitName }}</option>
                </select>
            </div>

            <div class="form-item required">
                <label class="label">联系地址：</label>
                <select class="input" v-model="form.address">
                    <option value="" disabled>请选择联系地址</option>
                    <option v-for="a in addressOptions" :key="a" :value="a">{{ a }}</option>
                </select>
            </div>

            <div class="form-item required">
                <label class="label">驾驶证有效日期：</label>
                <input class="input" type="date" v-model="form.licenseExpireDate" placeholder="请选择驾驶证有效日期" />
            </div>

            <div class="form-item">
                <label class="label">备 注：</label>
                <textarea class="textarea" v-model.trim="form.remark" placeholder="请输入备注信息"></textarea>
            </div>

            <div class="form-item">
                <label class="label">驾驶证照片：</label>
                <div class="upload-box" @click="triggerSelect">
                    <input ref="fileInput" class="file-input" type="file" accept="image/*" @change="onFileChange" />
                    <div v-if="!previewUrl" class="uploader">
                        <div class="plus">+</div>
                        <div class="text">上传图片</div>
                    </div>
                    <img v-else :src="previewUrl" class="preview" alt="preview" />
                </div>
            </div>

            <div class="form-actions">
                <button class="btn primary" :disabled="submitting" @click="handleSubmit">提交</button>
                <button class="btn" @click="handleCancel">取消</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { read, write } from '@/assets/Axios/axiosHttple'

interface CreateCargoOwnerDto {
    name: string
    phone: string
    company: string
    address: string
    licenseExpireDate: string
    remark: string
    licenseImageFile?: File | null
}

const form = reactive<CreateCargoOwnerDto>({
    name: '',
    phone: '',
    company: '',
    address: '',
    licenseExpireDate: '',
    remark: '',
    licenseImageFile: null
})

const submitting = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)
const previewUrl = ref<string>('')

// 外协单位下拉数据
type ExternalUnit = { id: number; unitName: string; address: string }
const externalUnitOptions = ref<ExternalUnit[]>([])
const addressOptions = ref<string[]>([])

async function loadExternalUnits() {
    try {
        const res = await read.get('baseinforead/api/External/GetExternalList', { params: { PageIndex: 1, PageSize: 2000 } })
        const json: any = res?.data ?? { data: [] }
        const list = Array.isArray(json?.data?.data) ? json.data.data : (Array.isArray(json?.data) ? json.data : [])
        externalUnitOptions.value = (list || []).map((x: any) => ({
            id: x.id,
            unitName: x.unitName ?? '',
            address: x.address ?? x.contactAddress ?? ''
        }))
    } catch (e) {
        console.error('加载外协单位失败', e)
        externalUnitOptions.value = []
    }
}

function onCompanyChange() {
    const match = externalUnitOptions.value.find(u => u.unitName === form.company)
    addressOptions.value = []
    if (match && match.address) {
        addressOptions.value = [match.address]
        form.address = match.address
    } else {
        form.address = ''
    }
}

function validate(): string | null {
    if (!form.name) return '请输入货主姓名'
    if (!form.phone) return '请输入手机号'
    if (!/^\d{6,20}$/.test(form.phone)) return '手机号格式不正确'
    if (!form.company) return '请输入单位名称'
    if (!form.address) return '请输入联系地址'
    if (!form.licenseExpireDate) return '请选择驾驶证有效日期'
    return null
}

function triggerSelect() { fileInput.value?.click() }

function onFileChange(e: Event) {
    const files = (e.target as HTMLInputElement).files
    if (!files || !files[0]) return
    const file = files[0]
    form.licenseImageFile = file
    const reader = new FileReader()
    reader.onload = () => { previewUrl.value = String(reader.result || '') }
    reader.readAsDataURL(file)
}

async function handleSubmit() {
    const msg = validate()
    if (msg) { alert(msg); return }
    submitting.value = true
    try {
        const payload = {
            id: 0,
            ownerName: form.name,
            phoneNumber: form.phone,
            unitName: form.company,
            contactAddress: form.address,
            licenseValidDate: form.licenseExpireDate ? new Date(form.licenseExpireDate).toISOString() : '',
            remarks: form.remark,
            licensePhoto: previewUrl.value || '',
            createdBy: localStorage.getItem('username') || 'system'
        }

        const res = await write.post('baseinfowrite/api/CargoOwner/CreateCargoOwnerInfo', payload)
        const json = res?.data
        if (res?.status === 200 && (json?.code === 200 || json?.data === true || typeof json?.data === 'number')) {
            window.location.href = '/GetCargoOwner?refresh=1'
        } else {
            console.error('新增失败', json)
            alert(json?.message || '新增失败')
        }
    } catch (e) {
        console.error('新增接口异常', e)
        alert('提交失败，请稍后重试')
    } finally {
        submitting.value = false
    }
}

// 初始化加载外协单位
loadExternalUnits()

function handleCancel() {
    if (window.history.length > 1) window.history.back()
}
</script>

<style scoped>
.add-cargo-owner-page {
    padding: 16px 20px;
    color: #333;
    font-size: 14px;
}

.page-title {
    font-size: 18px;
    margin-bottom: 12px;
}

.card {
    background: #fff;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
}

.form {
    padding: 16px;
    max-width: 720px;
}

.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 14px;
}

.form-item.required .label::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
}

.label {
    width: 120px;
    color: #666;
}

.input {
    flex: 1;
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
}

.textarea {
    flex: 1;
    min-height: 120px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px 10px;
}

.upload-box {
    width: 210px;
    height: 160px;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    background: #fafafa;
}

.file-input {
    position: absolute;
    opacity: 0;
    width: 0;
    height: 0;
}

.uploader {
    text-align: center;
    color: #909399;
}

.plus {
    font-size: 36px;
    line-height: 1;
}

.preview {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
}

.form-actions {
    margin-top: 18px;
    display: flex;
    gap: 10px;
}

.btn {
    height: 32px;
    padding: 0 16px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.btn.primary {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>
